<?php

class transfer {
	
	
	function transfer()
	{
		
	}
	
	// getTeamPlayerCodes() - function to return all player codes in this team
	function getTeamPlayerCodes($teamName)
	{
		$playerCode = array();
		$j = 0;
		
		$cDatabase = new database();

		$connect = $cDatabase->connectToDatabase();
		$activeDatabase = $cDatabase->getActiveDatabase($connect);
		
		$db = $cDatabase->selectDatabase($connect, $activeDatabase);
		
		$selectArray[0] = '*';
		$result = $cDatabase->selectFromDatabase($connect, 'memberlist', $selectArray, "teamName", $teamName, NULL, NULL);
		
		$finfo = mysqli_fetch_fields($result);
		$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
		
		for ($i = 1; $i <= MAXPLAYERS; $i++)
		{
			$playerCodeVariable = getPlayerCodeVariable($i);
			$playerWeekOutVariable = getPlayerWeekOutVariable($i);

			if ($row[$playerWeekOutVariable] == NULL)
			{	// We don't want to include players that we've transferred out as they're not in the current XI
				$j++;
				$playerCode[$j] = $row[$playerCodeVariable];
			}
		}
		$cDatabase->closeDatabase($connect);
		
		return $playerCode;
	}
	
	// getTransferPlayerCodes() - function to return all player codes in the database
	function getTransferPlayerCodes($playerTeamCode)
	{
		$playerCode = array();
		$j++;
		$flag = 0;
		
		$cDatabase = new database();

		$connect = $cDatabase->connectToDatabase();
		$activeDatabase = $cDatabase->getActiveDatabase($connect);
		
		$db = $cDatabase->selectDatabase($connect, $activeDatabase);
		
		$selectArray[0] = '*';
		$result = $cDatabase->selectFromDatabase($connect, 'playerlist', $selectArray, NULL, NULL, NULL, NULL);
		
		$finfo = mysqli_fetch_fields($result);
		
		for ($i = 0; $i <= mysqli_num_rows($result); $i++)
		{
			$flag = 0;
			$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
			// Check this player isn't already in our team, it shouldn't be possible to transfer in a current player
			for($k = 1; $k <= sizeof($playerTeamCode); $k++)
			{
				if ($row['playerCode'] == $playerTeamCode[$k])	// This player is in our team
					$flag = 1;
			}
			if (!$flag)
			{
				$playerCode[$j] = $row['playerCode'];
				$j++;		// Move index to next player
			}
		}
		$cDatabase->closeDatabase($connect);
		
		return $playerCode;
	}

	// getweeks() - function to return number of weeks
	function getWeeks()
	{
		$week = array();
		
		$cDatabase = new database();

		$connect = $cDatabase->connectToDatabase();
		$activeDatabase = $cDatabase->getActiveDatabase($connect);
		
		$db = $cDatabase->selectDatabase($connect, $activeDatabase);
		
		$selectArray[0] = '*';
		$result = $cDatabase->selectFromDatabase($connect, 'playerlist', $selectArray, NULL, NULL, NULL, NULL);
		
		// Get the number of weeks from the DB
		$finfo = mysqli_fetch_fields($result);
		
		$j = 0;
		/* Go through all fields */
		for ($i = 0; $i < mysqli_num_fields($result); $i++)
		{
			/* If the field starts with the word: week */
			if ( ( substr(trim($finfo[$i]->name), 0 , 4) == 'week'))
			{
				$j++;	// Use j so we don't count the previous columns as weeks
				$week[$j] = $j;
			}
		}
		// 2007-2008 bodge
		$j++;	// Use j so we don't count the previous columns as weeks
		$week[$j] = $j;
		$cDatabase->closeDatabase($connect);
		
		return $week;
	}

	// checkTeamTransfers() - function to check this team has enough available transfers
	function checkTeamTransfers($teamName)
	{	
		$transfersRemaining = 0;
		
		$cDatabase = new database();

		$connect = $cDatabase->connectToDatabase();
		$activeDatabase = $cDatabase->getActiveDatabase($connect);
		
		$db = $cDatabase->selectDatabase($connect, $activeDatabase);
		
		$selectArray[0] = '*';
		$result = $cDatabase->selectFromDatabase($connect, 'memberlist', $selectArray, 'teamName', $teamName, NULL, NULL);
		
		$finfo = mysqli_fetch_fields($result);
		$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
		
		// Check fields for playerWeekIn01 to playerWeekIn17
		// If all fields are occupied then we've already transferred in our max number of players
		for ($i = 1; $i <= MAXPLAYERS; $i++)
		{
			$playerCodeVariable = getPlayerCodeVariable($i);

			if ($row[$playerCodeVariable] == NULL)
				$transfersRemaining++;	// We've found a space so increment the spaceCounter
		}
		$cDatabase->closeDatabase($connect);
		
		return $transfersRemaining;
	}

	function checkTeam($teamName, $playerCodeIn, $playerCodeOut)
	{
		$error = 0;
		$j = 0;
		$k = 0;
		
		$cMember = new member;
		$cDatabase = new database();

		$connect = $cDatabase->connectToDatabase();
		$activeDatabase = $cDatabase->getActiveDatabase($connect);
		
		$db = $cDatabase->selectDatabase($connect, $activeDatabase);
		
		$selectArray[0] = '*';
		$result = $cDatabase->selectFromDatabase($connect, 'memberlist', $selectArray, 'teamName', $teamName, NULL, NULL);
		
		$finfo = mysqli_fetch_fields($result);
		$rowMemberList = mysqli_fetch_array($result, MYSQLI_ASSOC);
		
		for ($i = 1; $i <= MAXPLAYERS; $i++)
		{
			$playerCodeVariable = getPlayerCodeVariable($i);
			$playerWeekOutVariable = getPlayerWeekOutVariable($i);
			
			if ( ($rowMemberList[$playerWeekOutVariable] == NULL) && ($rowMemberList[$playerCodeVariable] != NULL) )		// All players not transferred out
			{	// Get all players which are or were in
				$selectArray[0] = 'playerCode';
				$selectArray[1] = 'playerPosition';
				$selectArray[2] = 'playerValue';
				$result = $cDatabase->selectFromDatabase($connect, 'playerlist', $selectArray, 'playerCode', $rowMemberList[$playerCodeVariable], NULL, NULL);
				
				$rowPlayerList = mysqli_fetch_array($result, MYSQLI_ASSOC);
				if (($rowPlayerList['playerValue'] != NULL) && ($rowPlayerList['playerPosition'] != NULL))
				{
					$cMember->addFormation($rowPlayerList['playerPosition']);
					$cMember->addPlayerValue($rowPlayerList['playerValue']);
				}
				else
					$error = 2;
			}
		}
		echo "<BR>Old team value ".$cMember->getTeamValue()."m Old formation ".$cMember->getCurrentFormation();

		// Add on the value and position of the player being transferred in
		$result = $cDatabase->selectFromDatabase($connect, 'playerlist', $selectArray, 'playerCode', $playerCodeIn, NULL, NULL);
		$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
		$cMember->addPlayerValue($row['playerValue']);
		$error |= $cMember->addFormation($row['playerPosition']);
		
		// Remove the value and position of the player being transferred out
		$result = $cDatabase->selectFromDatabase($connect, 'playerlist', $selectArray, 'playerCode', $playerCodeOut, NULL, NULL, NULL, NULL);
		$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
		$cMember->subtractPlayerValue($row['playerValue']);
		$error |=$cMember->removeFromFormation($row['playerPosition']);

		echo "<BR>New team value ".$cMember->getTeamValue()."m New formation ".$cMember->getCurrentFormation();
		
		// Check the team value is valid
		if ($cMember->getTeamValue() > MAXVALUE)
		{
			echo "<BR>This transfer code[".$playerCodeIn."] in code[".$playerCodeOut."] gives team value ".$cMember->getTeamValue;
			$error |= 3;
		}
		
		// Check this formation is valid
		$error |= $cMember->checkFormation();
			
		$cDatabase->closeDatabase($connect);
		
		return $error;
	}
	
	function selectTransfer($teamName, $transfersRemaining)
	{
		$cDatabase = new database();

		$connect = $cDatabase->connectToDatabase();
		$activeDatabase = $cDatabase->getActiveDatabase($connect);
			
		$db = $cDatabase->selectDatabase($connect, $activeDatabase);
		$selectArray[0] = 'playerName';

		echo "<BR>".$teamName." has ".$transfersRemaining." transfers remaining";
		// Get all current players in team
		$playerTeamCode = $this->getTeamPlayerCodes($teamName);

		// Get all possible players to transfer in
		$playerTransferCode = $this->getTransferPlayerCodes($playerTeamCode);
	
		// Get possible weeks
		$week = $this->getWeeks();
	
		// Options - Player to transfer out, player to transfer in, week
		?>
		<form action="<?php echo $_SERVER['PHP_SELF'] ?>?form=submitTransfer" method="POST">
	  		<table border='0'>
				<tr><td>
	    			<select name="selectTeamName">
					<?php
		    		  		echo"<option value = '" .$teamName. "'>" .$teamName. "</option>";
					?>
			        </select>
		    		Name
				</td>
				</tr>
				<tr><td>
	    			<select name="selectPlayerOut">
					<?php
					for ($i = 1; $i <= sizeof($playerTeamCode); $i++)
					{
						$playerResult = $cDatabase->selectFromDatabase($connect, 'playerlist', $selectArray, "playerCode", $playerTeamCode[$i], NULL, NULL);
						$row = mysqli_fetch_array($playerResult, MYSQLI_ASSOC);
						
						if ($playerTeamCode[$i] != NULL)
	    		  			echo"<option value = '" .$playerTeamCode[$i]. "'>" .$playerTeamCode[$i]." - ".$row['playerName']. "</option>";
					}
					?>
			        </select>
		    		Player Out
				</td>
				</tr>
				<tr><td>
					<select name="selectPlayerIn">
					<?php
					for ($i = 0; $i <= sizeof($playerTransferCode); $i++)
					{
						$playerResult = $cDatabase->selectFromDatabase($connect, 'playerlist', $selectArray, "playerCode", $playerTransferCode[$i], NULL, NULL);
						$row = mysqli_fetch_array($playerResult, MYSQLI_ASSOC);
						
						if ($playerTransferCode[$i] != NULL)
	    		  			echo"<option value = '" .$playerTransferCode[$i]. "'>" .$playerTransferCode[$i]." - ".$row['playerName']. "</option>";
					}
					?>
			        </select>
		    		Player In
				</td></tr>
				<tr><td>
					<select name="selectWeek">
					<?php
					for ($i = 1; $i <= sizeof($week); $i++)
					{
		    		  	echo"<option value = '" .$week[$i]. "'>" .$week[$i]. "</option>";
					}
					?>
			        </select>
					Week
				</td></tr>
		    		<input name="submitTransfer" type="submit" id="submitTransfer" value="Submit Transfer">
			
				<tr></td>
				  <INPUT TYPE="BUTTON" VALUE="Main Menu" ONCLICK="window.location.href='http://localhost'">
			 	</td></tr>
		  	</table>
		</form>
		<?php
	}
	
	function doTransfer($teamName, $playerCodeIn, $playerCodeOut, $week)
	{
		$cDatabase = new database();

		$connect = $cDatabase->connectToDatabase();
		$activeDatabase = $cDatabase->getActiveDatabase($connect);
	
		$db = $cDatabase->selectDatabase($connect, $activeDatabase);
	
		$selectArray[0] = '*';
		$result = $cDatabase->selectFromDatabase($connect, 'memberlist', $selectArray, 'teamName', $teamName, NULL, NULL);

		// Find a space for the new player
		$finfo = mysqli_fetch_fields($result);
		$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
		for ($i = 1; $i <= MAXPLAYERS; $i++)
		{
			$playerCodeVariable = getPlayerCodeVariable($i);
			$playerWeekInVariable = getPlayerWeekInVariable($i);
			$playerWeekOutVariable = getPlayerWeekOutVariable($i);

			if ( ($row[$playerCodeVariable] == NULL) && ($row[$playerWeekInVariable] == NULL) && (!$flagA) )
			{	// Here we locate the next free column to add the playerCodeIn and playerWeekIn
				$queryAddPlayerCode = "UPDATE memberlist SET ".$playerCodeVariable." = '".$playerCodeIn."' WHERE teamName='".$teamName."'";
				$queryAddWeekIn = "UPDATE memberlist SET ".$playerWeekInVariable." = '".$week."' WHERE teamName='".$teamName."'";
				$flagA = 1;	// Set the flag so we don't add these values more than once
			}
			if ( ($row[$playerCodeVariable] == $playerCodeOut) && (!$flagB) )
			{	// Here we locate the next free column to add the playerWeekOut
				$queryAddWeekOut = "UPDATE memberlist SET ".$playerWeekOutVariable." = '".$week."' WHERE teamName='".$teamName."'";
				$flagB = 1;	// Set the flag so we don't add these values more than once
			}
		}
		
		echo "$queryAddWeekOut";
		if ( ($queryAddPlayerCode != NULL) && ($queryAddWeekIn != NULL) && ($queryAddWeekOut != NULL) )
		{
			$result = mysqli_query($connect, $queryAddPlayerCode);
			$result = mysqli_query($connect, $queryAddWeekIn);
			$result = mysqli_query($connect, $queryAddWeekOut);
		}
		// Print info for announcements page
	
		$selectArray[0] = '*';
		$result = $cDatabase->selectFromDatabase($connect, 'playerlist', $selectArray, "playerCode", $playerCodeOut, NULL, NULL);
		$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
		$playerNameOut = $row['playerName'];
		$playerTeamOut = $row['playerTeam'];
		$playerValueOut = $row['playerValue'];
		
		$result = $cDatabase->selectFromDatabase($connect, 'playerlist', $selectArray, "playerCode", $playerCodeIn, NULL, NULL);
		$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
		$playerNameIn = $row['playerName'];
		$playerTeamIn = $row['playerTeam'];
		$playerValueIn = $row['playerValue'];
		echo"\n";
		
		echo"
		<tr class=\"style3\">
            <td width=\"51\" bgcolor=\"#FFFFFF\" class=\"style13\">OUT</td>
            <td width=\"51\" bgcolor=\"#FFFFFF\" class=\"style13\">".$playerCodeOut."</td>
            <td width=\"103\" bgcolor=\"#FFFFFF\" class=\"style13\">".$playerNameOut."<FONT color=#0033ff>&nbsp;</FONT></td>
            <td width=\"51\" bgcolor=\"#FFFFFF\" class=\"style13\">".$playerTeamOut."</td>
            <td width=\"51\" bgcolor=\"#FFFFFF\" class=\"style13\">".$playerValueOut."</td>
            <td width=\"51\" class=\"style13\">IN</td>
            <td width=\"51\" class=\"style13\">".$playerCodeIn."</td>
            <td width=\"103\" class=\"style13\">".$playerNameIn."</td>
            <td width=\"51\" class=\"style13\">".$playerTeamIn."</td>
            <td width=\"50\" class=\"style13\">".$playerValueIn."</td>
         </tr>";
		  
		echo"\n";
		mysqli_close($connect);
	}
	
	function getPlayerName($playerCode)
	{
		$cDatabase = new database();

		$connect = $cDatabase->connectToDatabase();
		$activeDatabase = $cDatabase->getActiveDatabase($connect);
	
		$db = $cDatabase->selectDatabase($connect, $activeDatabase);
	
		$selectArray[0] = '*';
		$result = $cDatabase->selectFromDatabase($connect, 'playerlist', $selectArray, "playerCode", $playerCode, NULL, NULL);
		$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
		return $row['playerName'];
	}
	
	function getCaptainCodeForWeek($teamName, $week)
	{
		// Get captain for current week
		$cDatabase = new database();

		$connect = $cDatabase->connectToDatabase();
		$activeDatabase = $cDatabase->getActiveDatabase($connect);
	
		$db = $cDatabase->selectDatabase($connect, $activeDatabase);
	
		$selectArray[0] = '*';
		$result = $cDatabase->selectFromDatabase($connect, 'memberlist', $selectArray, 'teamName', $teamName, NULL, NULL);

		//$finfo = mysqli_fetch_fields($result);
		$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
		
		$captainVariable = getCaptainVariable($week);
		return $row[$captainVariable];
	}
	
	function checkCaptainTransferOK($day, $currentWeek)
	{
		// Special cases:
		// Week3: No premiership games until Saturday
		if (($currentWeek == 1) || ($currentWeek == 2) || ($currentWeek == 3) || ($currentWeek == 4) || ($currentWeek == 5)
			|| ($currentWeek == 6) || ($currentWeek == 7) || ($currentWeek == 8) || ($currentWeek == 9) || ($currentWeek == 10)
			|| ($currentWeek == 11) || ($currentWeek == 12) || ($currentWeek == 13) || ($currentWeek == 14) || ($currentWeek == 15)
			|| ($currentWeek == 16) || ($currentWeek == 17) || ($currentWeek == 18) || ($currentWeek == 19))
		{
			switch ($day)
			{
			case 'Saturday'	:	
			case 'Sunday'	:	return 0;
			default			:	return 1;
			}
		}
		else
		{
			// Can only do captain transfers on Monday or Tuesday to be safe
			switch ($day)
			{
			case 'Monday'	:	return 1;
			case 'Tuesday'	:	return 1;
			default			:	return 0;
			}
		}
	}
}
?>